<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>旋转元素</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }
      body {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 100vh;
      }
      .box {
        width: 140px;
        height: 100px;
        background-color: red;
      }
    </style>
  </head>
  <body>
    <div class="box"></div>

    <script>
      const box = document.querySelector(".box");

      document.addEventListener(
        "mousemove",
        (ev) => {
          const { x, y, width, height } = box.getBoundingClientRect();

          // 元素中心坐标
          const boxCenterX = x + width / 2;
          const boxCenterY = y + height / 2;

          // 邻边
          const distX = ev.clientX - boxCenterX;
          // 对边
          const distY = ev.clientY - boxCenterY;

          // 转成角度
          const angle = (Math.atan2(distY, distX) * 180) / Math.PI;

          box.style.transform = `rotate(${angle - 90}deg)`;
        },
        false
      );
    </script>
  </body>
</html>
